﻿using NLog;
using NLog.Config;
using NLog.Targets;

public sealed class NLogHelper
{
    private static readonly NLogHelper instance = new NLogHelper();
    private readonly Logger logger;

    static NLogHelper()
    {
    }

    private NLogHelper()
    {
        // 注册自定义目标
        var customTarget = new MessageLogTarget();
        LogManager.Configuration.AddTarget("MessageLogTarget", customTarget);
        var rule = new LoggingRule("*", LogLevel.Trace, customTarget);
        LogManager.Configuration.LoggingRules.Add(rule);
        LogManager.ReconfigExistingLoggers();

        logger = LogManager.GetCurrentClassLogger();
    }

    public static NLogHelper Instance
    {
        get
        {
            return instance;
        }
    }

    public void Trace(string message)
    {
        logger.Trace(message);
    }

    public void Debug(string message)
    {
        logger.Debug(message);
    }

    public void Info(string message)
    {
        logger.Info(message);
    }

    public void Warn(string message)
    {
        logger.Warn(message);
    }

    public void Error(string message)
    {
        logger.Error(message);
    }

    public void Fatal(string message)
    {
        logger.Fatal(message);
    }
}

[Target("MessageLogTarget")]
public class MessageLogTarget : TargetWithLayout
{
    public static event Action<string> LogMessageReceived;

    protected override void Write(LogEventInfo logEvent)
    {
        string logMessage = Layout.Render(logEvent);
        LogMessageReceived?.Invoke(logEvent.Message);
    }
}